package com.axjy.auth.uitl;

import com.axjy.commons.vo.Result;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.concurrent.TimeUnit;

@Component
public class AuthInterceptor implements HandlerInterceptor {

    @Resource
    private TokenUtil tokenUtil;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        System.out.println(tokenUtil);

       String token=request.getHeader("token");

        System.out.println("=======>"+token);
       Long userId=  tokenUtil.checkToken(token);

       if(userId.equals(-1)){
           response.setContentType("application/json;charset=UTF-8");
           PrintWriter out= response.getWriter();
           Result result=Result.fail("登录失败!");
           ObjectMapper objectMapper=new ObjectMapper();
           String json=objectMapper.writeValueAsString(result);
           out.print(json);
           return false;
       }

        ValueOperations ops= stringRedisTemplate.opsForValue();
        boolean flag=ops.setIfPresent("token:"+Long.toString(userId),token,20, TimeUnit.MINUTES);
        if(flag==false){
            response.setContentType("application/json;charset=UTF-8");
            PrintWriter out= response.getWriter();
            Result result=Result.fail("登录失败!");
            ObjectMapper objectMapper=new ObjectMapper();
            String json=objectMapper.writeValueAsString(result);
            out.print(json);
            return false;
        }
        return true;
    }
}
